﻿using AutoMapper;
using MediatR;
using SCM.API.Write.Application.Command.PurchaseRefund;
using SCM.Domain;
using SCM.ErrorCode;
using SCM.Infrastructure.Implement;
using SCM.Infrastructure.Interface;
using System.Security.Claims;
using System.Transactions;
using Warehouse.Domian.Model;

namespace SCM.API.Write.Application.Handler.PurchaseRefund
{
    public class AddPurchaseRefundHandler : IRequestHandler<AddPurchaseRefundCommand, APIResult<int>>
    {
        IMapper mapper;
        DatabaseContext db;
        ILogger<AddPurchaseRefundHandler> logger;
        private readonly IHttpContextAccessor _httpContextAccessor;
        public AddPurchaseRefundHandler(IMapper mapper, DatabaseContext db, ILogger<AddPurchaseRefundHandler> logger = null, IHttpContextAccessor httpContextAccessor = null)
        {

            this.mapper = mapper;
            this.db = db;
            this.logger = logger;
            _httpContextAccessor = httpContextAccessor;
        }

        public async Task<APIResult<int>> Handle(AddPurchaseRefundCommand request, CancellationToken cancellationToken)
        {
            try
            {
                APIResult<int> result = new APIResult<int>();
                var model = mapper.Map<PurchaseRefundModel>(request);


                ////获取创建人id
                //var userIdClaim = _httpContextAccessor.HttpContext.User.FindFirstValue(ClaimTypes.NameIdentifier);
                //if (!int.TryParse(userIdClaim, out int userId))
                //{
                //    result.Code = APIEnum.Fail;
                //    result.Msg = "无法获取有效的用户ID";
                //    return await Task.FromResult(result);
                //}
                //model.MadeName = userId;
                //model.MadeTime = DateTime.Now;
                //model.UpdateName = null;
                //model.CreateTime = null;

                var purchas = db.SqlSugar.Queryable<PurchaseRefundModel>().Where(c => c.RefundNum == request.RefundNum && !c.IsDel).Count();
                if (purchas > 0)
                {
                    logger.LogError("退货单号唯一");
                    result.Code = APIEnum.Fail;
                    result.Msg = "退货单号唯一";
                    return await Task.FromResult(result);
                }
                if (string.IsNullOrEmpty(model.RefundNum))
                {
                    result.Code = APIEnum.Fail;
                    result.Msg = "退货单号不能为空";
                    return await Task.FromResult(result);
                }

                if (model.Num <= 0)
                {
                    result.Code = APIEnum.Fail;
                    result.Msg = "退货数量必须大于 0";
                    return await Task.FromResult(result);
                }
                var purchaseExists = await db.SqlSugar.Queryable<PurchaseManagementModel>().Where(p => p.PurchaseId == request.PurchaseId).FirstAsync();
                if (purchaseExists == null)
                {
                    result.Code = APIEnum.Fail;
                    result.Msg = $"采购单{request.PurchaseId}不存在，无法退货";
                    result.Data = 0;
                    return await Task.FromResult(result);
                }

                if (purchaseExists.State == 1)
                {
                    result.Code = APIEnum.Fail;
                    result.Msg = $"采购单状态为{purchaseExists.State}，不允许退货";
                    return await Task.FromResult(result);
                }


                

               

                if (request.State < 1 || request.State > 3)
                {
                    result.Code = APIEnum.Fail;
                    result.Msg = "状态值只能为1~3";
                    result.Data = 0;
                    return await Task.FromResult(result);
                }

                //// 退货数量等于采购单的实际数量
                //var purchaseOrder = await db.SqlSugar.Queryable<PurchaseManagementModel>().Where(p => p.PurchaseId == model.PurchaseId).FirstAsync();

                //if (model.Num == purchaseOrder.Num)
                //{
                //    result.Code = APIEnum.Fail;
                //    result.Msg = $"退货数量超过原采购单收货量：采购收货 {purchaseOrder.Num}，申请退货 {model.Num}";
                //    return await Task.FromResult(result);
                //}
                db.SqlSugar.BeginTran();

                int r = db.SqlSugar.Insertable(model).ExecuteCommand();

                var purchaseManagementModel = await db.SqlSugar.Queryable<PurchaseManagementModel>().Where(p => p.PurchaseId == request.PurchaseId).FirstAsync();
                purchaseManagementModel.Refund = "退";
                await db.SqlSugar.Updateable(purchaseManagementModel).ExecuteCommandAsync();

                db.SqlSugar.CommitTran();

                result.Msg = "添加采购退货单信息成功";
                result.Data = r;
                result.Code = APIEnum.Success;
                return await Task.FromResult(result);
            }
            catch (Exception ex)
            {
                db.SqlSugar.RollbackTran();
                logger.LogError(ex.Message, "处理采购退货添加时发生异常");
                throw;
            }
        }
    }
}
